/**
 * @description 请求拦截器和响应拦截器基于uview的http模块进行封装
 * @author yinzhi
 * @date 2025-03-03
 */
import { http } from '@/uni_modules/uview-plus'
import { store } from '@/libs/store/index'
const { auth } = store.state

// 白名单配置（支持正则） 防止后端接口没做过滤 导致不需要token的接口传入后报错
const WHITE_LIST = [
    // '/app/user/auth/getOpenPhone/login',
    // '/app/user/hotelBaseInfo/getById/detail',
    // '/app/user/image/get/imageListByTwoCategory',
    // '/app/user/room/get/roomPageList',
    // '/app/user/hotelBaseInfo/get/notice'
    // /^\/public\// // 匹配所有/public/开头的路由
]

// 请求拦截器
const requestInterceptors = vm => {
    http.interceptors.request.use(
        config => {
            uni.hideLoading()
            // 防御性处理
            config.data = config.data || {}
            config.header = config.header || {}

            // 白名单检查
            const needToken = !WHITE_LIST.some(pattern =>
                typeof pattern === 'string' ? config.url === pattern : pattern.test(config.url)
            )
            if (needToken) {
                const token = auth.token || ''
                if (token) {
                    config.header.Authorization = token
                }
            }
            return config
        },
        error => {
            uni.hideLoading()
            return Promise.reject(error)
        }
    )
}

// 响应拦截器
const responseInterceptors = vm => {
    http.interceptors.response.use(
        response => {
            uni.hideLoading()

            // 统一响应结构
            let result = {
                data: response?.data?.data || {},
                status: response.statusCode || response?.data?.status || 200,
                message: response?.data?.msg || '',
                headers: response.headers
            }
            if (response.statusCode === 200 && response?.data?.status !== 200) {
                result.status = response?.data?.status
            }
            // 状态码处理
            switch (result.status) {
                case 200:
                    return result.data
                case 401: // 登录过期处理
                    clearAuth()
                    return showReLoginToast()
                // return Promise.reject(result)
                case 403:
                    return handle403Error(result)
                default:
                    showErrorToast(result.message)
                    return Promise.reject(result)
            }
        },
        error => {
            uni.hideLoading()
            return Promise.reject(error)
        }
    )
}

// 清除token
async function clearAuth() {
    await store.commit('auth/setToken', '')
    await store.dispatch('auth/checkWxCode')
}
// 显示重新登录toast
function showReLoginToast() {
    uni.showModal({
        title: '登录过期提示',
        content: '请重新登录，再继续操作/访问！',
        icon: 'none',
        showCancel: false,
        confirmText: '返回首页',
        success: res => {
            if (res.confirm) {
                uni.reLaunch({ url: '/pages/index/index' })
            }
        }
    })
}
// 显示错误toast
function showErrorToast(msg) {
    uni.showToast({
        title: msg || '请求失败，请稍后重试',
        icon: 'none',
        duration: 2000
    })
}

// 403处理
function handle403Error(result) {
    uni.showModal({
        title: '权限不足',
        content: result.message || '当前操作未被授权',
        showCancel: false
    })
    return Promise.reject(result)
}

export { requestInterceptors, responseInterceptors }
